﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: PermutationGenomeBase.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-12-08 8:26 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Linq;
using BOL.Linq;

namespace BOL.Algorithms.Optimization.EvolutionaryAlgorithms
{
    public abstract class PermutationGenomeBase : ArrayGenomeBase<int>
    {
        #region Constructor

        protected PermutationGenomeBase(Random random, int[] sequence)
            : base(random, sequence)
        {
            if (Length != sequence.Distinct().Count())
                throw new ArgumentException("There should not be any duplicated element.");
        }

        protected PermutationGenomeBase(Random random, int length)
            : this(random, Enumerable.Range(0, length).OrderByRandom(random).ToArray()) { }

        #endregion

        #region Public methods

        private void Crossover(PermutationGenomeBase other)
        {
            if (Length != other.Length)
                throw new ArgumentException();

            var point = Random.Next(Length);

            var fGenome1 = Sequence.Take(point).ToArray();
            var tGenome2 = other.Sequence.Except(fGenome1);
            var mGenome2 = other.Sequence.Skip(point).Take(Length - point).ToArray();
            var tGenome1 = Sequence.Except(mGenome2);

            Sequence = fGenome1.Concat(tGenome2).ToArray();
            other.Sequence = tGenome1.Concat(mGenome2).ToArray();
        }

        public override void Crossover(IGenome<int> other)
        {
            Crossover(other as PermutationGenomeBase);
            if (other is PermutationGenomeBase)
                Crossover(other as PermutationGenomeBase);
            else
                throw new InvalidCastException("Other is not a PermutationGenomeBase type.");
        }

        public override void Mutate(double mutationRate)
        {
            var array = new int[Length];
            Array.Copy(Sequence, array, Length);

            var range = Enumerable.Range(0, Length).OrderByRandom(Random).Take(2).ToArray();
            var from = range.Min();
            var to = range.Max();

            var tmp = array.ElementAt(from);
            array[from] = array.ElementAt(to);
            array[to] = tmp;

            Sequence = array;
        }

        #endregion
    }
}
